package com.cskaoyan.service;

import com.cskaoyan.bean.*;
import com.cskaoyan.bo.UpdateGoodsBo;
import com.cskaoyan.mapper.*;
import com.cskaoyan.vo.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    GoodsAttributeMapper goodsAttributeMapper;
    @Autowired
    GoodsProductMapper goodsProductMapper;
    @Autowired
    GoodsSpecificationMapper goodsSpecificationMapper;
    @Autowired
    CommentMapper commentMapper;
    @Autowired
    BrandMapper brandMapper;
    @Autowired
    CategoryMapper categoryMapper;

    //事务
    @Autowired
    private PlatformTransactionManager platformTransactionManager;

    /**
     * 获取商品列表
     */
    @Override
    public GoodsListVo getGoodsList(Integer page, Integer limit, String sort, String order, String goodsSn, String name) {

        PageHelper.startPage(page, limit);

        GoodsExample goodsExample = new GoodsExample();
        goodsExample.setOrderByClause(sort + " " + order);
        GoodsExample.Criteria criteria = goodsExample.createCriteria();
        //模糊查询条件
        if (name != null) {
            criteria.andNameLike("%" + name + "%");
        }
        if (goodsSn != null) {
            criteria.andGoodsSnLike("%" + goodsSn + "%");
        }
        //只查询未删除的商品
        criteria.andDeletedEqualTo(false);
        List<Goods> goods = goodsMapper.selectByExample(goodsExample);

        //通过PageInfo获取分页信息
        PageInfo<Goods> goodsPageInfo = new PageInfo<>(goods);
        long total = goodsPageInfo.getTotal();

        GoodsListVo goodsListVo = new GoodsListVo();
        goodsListVo.setTotal(total);
        goodsListVo.setItems(goods);
        return goodsListVo;
    }

    /**
     * 删除商品信息
     */
    @Override
    @Transactional
    public int delete(Goods goods) {

        //拿到商品id
        Integer id = goods.getId();

        goods.setDeleted(true);
        int i = 0;

        try {
            i = goodsMapper.updateByPrimaryKey(goods);
            if (i <= 0) {
                throw new RuntimeException("商品删除失败");
            }
            goodsProductMapper.updateDeleted(id, true);
            goodsAttributeMapper.updateDeleted(id, true);
            goodsSpecificationMapper.updateDeleted(id, true);
            //删除评论
            commentMapper.updateDeleted(id, true);
            //删除图片
            String picUrl = goods.getPicUrl();
            if (picUrl != null && !picUrl.equals("")) {
                categoryMapper.updateDeleted(picUrl, true);
            }

        } catch (Exception e) {
            e.printStackTrace();
            //事务回滚
            platformTransactionManager.rollback(TransactionAspectSupport.currentTransactionStatus());
            return 404;
        }

        return 200;
    }

    /**
     * 查询品牌和分类
     */
    @Override
    public CatAndBrandVo getCatAndBrand() {

        List<Brand> brands = brandMapper.selectAll();
        ArrayList<ValueLabelVo> brandArrayList = new ArrayList<>();

        for (Brand brand : brands) {
            ValueLabelVo brandList = new ValueLabelVo();
            brandList.setValue(brand.getId());
            brandList.setLabel(brand.getName());
            brandArrayList.add(brandList);
        }

        //分类
        ArrayList<ValueLabelChildrenVo> catArrayList = new ArrayList<>();
        List<Category> categories = categoryMapper.selectAll();

        for (Category category : categories) {
            ValueLabelChildrenVo fatherCategory = new ValueLabelChildrenVo();
            fatherCategory.setValue(category.getId());
            fatherCategory.setLabel(category.getName());

            //拿到id
            Integer id = category.getId();

            List<Category> categoriesChildren = categoryMapper.selectAllByPid(id);

            ArrayList<ValueLabelVo> valueLabelVos = new ArrayList<>();
            for (Category categoriesChild : categoriesChildren) {
                ValueLabelVo catChildrenList = new ValueLabelVo();
                catChildrenList.setLabel(categoriesChild.getName());
                catChildrenList.setValue(categoriesChild.getId());
                valueLabelVos.add(catChildrenList);
            }
            fatherCategory.setChildren(valueLabelVos);
            catArrayList.add(fatherCategory);
        }

        CatAndBrandVo catAndBrandVo = new CatAndBrandVo();
        catAndBrandVo.setCategoryList(catArrayList);
        catAndBrandVo.setBrandList(brandArrayList);
        return catAndBrandVo;
    }


    @Override
    public GoodsDetailVo getDetail(Integer id) {

        //要返回的对象
        GoodsDetailVo goodsDetailVo = new GoodsDetailVo();

        //Attribute
        GoodsAttributeExample goodsAttributeExample = new GoodsAttributeExample();
        GoodsAttributeExample.Criteria goodsAttributeExampleCriteria = goodsAttributeExample.createCriteria();
        goodsAttributeExampleCriteria.andGoodsIdEqualTo(id);
        goodsAttributeExampleCriteria.andDeletedEqualTo(false);
        List<GoodsAttribute> goodsAttributes = goodsAttributeMapper.selectByExample(goodsAttributeExample);
        goodsDetailVo.setAttributes(goodsAttributes);

        //goods
        Goods goods = goodsMapper.selectByPrimaryKey(id);
        GoodsGalleryList generate = GoodsGalleryList.generate(goods);
        goodsDetailVo.setGoods(generate);

        //categoryIds
        //先查第二级
        ArrayList<Integer> categoryIds = new ArrayList<>();
        Integer categoryId = goods.getCategoryId();
        //第一级
        Category category = categoryMapper.selectByPrimaryKey(categoryId);
        if (category != null) {
            Integer categoryFatherId = category.getId();
            categoryIds.add(categoryFatherId);
        }
        categoryIds.add(categoryId);
        goodsDetailVo.setCategoryIds(categoryIds);

        //products
        GoodsProductExample goodsProductExample = new GoodsProductExample();
        GoodsProductExample.Criteria goodsProductExampleCriteria = goodsProductExample.createCriteria();
        goodsProductExampleCriteria.andGoodsIdEqualTo(id);
        goodsProductExampleCriteria.andDeletedEqualTo(false);
        List<GoodsProduct> goodsProducts = goodsProductMapper.selectByExample(goodsProductExample);
        goodsDetailVo.setProducts(goodsProducts);

        //specifications
        GoodsSpecificationExample goodsSpecificationExample = new GoodsSpecificationExample();
        GoodsSpecificationExample.Criteria goodsSpecificationExampleCriteria = goodsSpecificationExample.createCriteria();
        goodsSpecificationExampleCriteria.andGoodsIdEqualTo(id);
        goodsSpecificationExampleCriteria.andDeletedEqualTo(false);
        List<GoodsSpecification> goodsSpecifications = goodsSpecificationMapper.selectByExample(goodsSpecificationExample);
        goodsDetailVo.setSpecifications(goodsSpecifications);

        return goodsDetailVo;
    }

    @Override
    @Transactional
    public int update(GoodsDetailVo goodsDetailVo) {

        try {

            //先删除
            GoodsGalleryList goods = goodsDetailVo.getGoods();
            Goods generate = Goods.generate(goods);
            int delete = delete(generate);
            if (delete == 404) {
                throw new RuntimeException("更新商品前删除失败");
            }

            List<GoodsAttribute> attributes = goodsDetailVo.getAttributes();
            int i = 0;
            for (GoodsAttribute attribute : attributes) {
                attribute.setGoodsId(goods.getId());

                if (attribute.getId() != 0) {
                    attribute.setUpdateTime(new Date(System.currentTimeMillis()));
                    attribute.setDeleted(false);
                    i = goodsAttributeMapper.updateByPrimaryKey(attribute);

                } else {
                    attribute.setAddTime(new Date(System.currentTimeMillis()));
                    attribute.setUpdateTime(new Date(System.currentTimeMillis()));
                    attribute.setDeleted(false);

                    i = goodsAttributeMapper.insert(attribute);
                }
                if (i <= 0) {
                    throw new RuntimeException("goodsAttribute更新失败");
                }
            }

            generate.setDeleted(false);
            generate.setUpdateTime(new Date(System.currentTimeMillis()));
            i = goodsMapper.updateByPrimaryKey(generate);
            if (i <= 0) {
                throw new RuntimeException("goods更新失败");
            }

            List<GoodsProduct> products = goodsDetailVo.getProducts();
            for (GoodsProduct product : products) {
                product.setGoodsId(goods.getId());
                if (product.getId() != 0) {
                    product.setUpdateTime(new Date(System.currentTimeMillis()));
                    product.setDeleted(false);
                    i = goodsProductMapper.updateByPrimaryKey(product);
                } else {
                    product.setAddTime(new Date(System.currentTimeMillis()));
                    product.setUpdateTime(new Date(System.currentTimeMillis()));
                    product.setDeleted(false);
                    i = goodsProductMapper.insert(product);
                }
                if (i <= 0) {
                    throw new RuntimeException("goodsProduct更新失败");
                }
            }

            List<GoodsSpecification> specifications = goodsDetailVo.getSpecifications();

            for (GoodsSpecification specification : specifications) {
                specification.setGoodsId(goods.getId());
                if (specification.getId() != null) {
                    specification.setUpdateTime(new Date(System.currentTimeMillis()));
                    i = goodsSpecificationMapper.updateByPrimaryKey(specification);
                } else {
                    specification.setAddTime(new Date(System.currentTimeMillis()));
                    specification.setUpdateTime(new Date(System.currentTimeMillis()));
                    specification.setDeleted(false);
                    i = goodsSpecificationMapper.insert(specification);
                }

                if (i <= 0) {
                    throw new RuntimeException("goodsSpecificationMapper");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return 404;
        }
        return 200;
    }


    @Override
    @Transactional
    public int create(UpdateGoodsBo updateGoodsBo) {

        GoodsGalleryList goods = updateGoodsBo.getGoods();
        Goods generate = Goods.generate(goods);
        generate.setAddTime(new Date(System.currentTimeMillis()));
        generate.setUpdateTime(new Date(System.currentTimeMillis()));
        generate.setDeleted(false);
        int insert = goodsMapper.insert(generate);
        if (insert <= 0) {
            throw new RuntimeException("商品插入失败");
        }
        int id = generate.getId();

        try {
            List<GoodsAttribute> attributes = updateGoodsBo.getAttributes();
            int i = 0;
            for (GoodsAttribute attribute : attributes) {
                attribute.setGoodsId(id);
                attribute.setAddTime(new Date(System.currentTimeMillis()));
                attribute.setUpdateTime(new Date(System.currentTimeMillis()));
                attribute.setDeleted(false);
                i = goodsAttributeMapper.insert(attribute);
                if (i <= 0) {
                    throw new RuntimeException("goodsAttribute更新失败");
                }
            }

            List<GoodsProduct> products = updateGoodsBo.getProducts();
            for (GoodsProduct product : products) {
                product.setGoodsId(id);
                product.setAddTime(new Date(System.currentTimeMillis()));
                product.setUpdateTime(new Date(System.currentTimeMillis()));
                product.setDeleted(false);
                i = goodsProductMapper.insert(product);
                if (i <= 0) {
                    throw new RuntimeException("goodsProduct更新失败");
                }
            }

            List<GoodsSpecification> specifications = updateGoodsBo.getSpecifications();
            for (GoodsSpecification specification : specifications) {
                specification.setGoodsId(id);
                specification.setAddTime(new Date(System.currentTimeMillis()));
                specification.setUpdateTime(new Date(System.currentTimeMillis()));
                specification.setDeleted(false);
                i = goodsSpecificationMapper.insert(specification);
                if (i <= 0) {
                    throw new RuntimeException("goodsSpecificationMapper");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return 404;
        }
        return 200;
    }
}
